package com.bt.springboot.demo.socket;

import com.bt.springboot.common.util.SocketUtil;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * @author zkx
 * @Date 2023/5/6 14:40
 */
@Component
@Slf4j
public class SocketHandler {

	@Autowired
	private SocketIOServer socketIOServer;

	@PostConstruct
	private void start(){
		try {
			socketIOServer.start();
		} catch (Exception e) {
			log.error("",e);
		}
	}

	@PreDestroy
	private void destroy(){
		try {
			socketIOServer.stop();
		} catch (Exception e) {
			log.error("",e);
		}
	}

	@OnConnect
	public void connect(SocketIOClient client){
		String userFlag = client.getHandshakeData().getSingleUrlParam("userFlag");
		SocketUtil.connectMap.put(userFlag,client);
		log.info("客户端userFlag: " + userFlag + "已连接");
	}

	@OnDisconnect
	public void onDisConnect(SocketIOClient client){
		String userFlag = client.getHandshakeData().getSingleUrlParam("userFlag");
		log.info("客户端userFlag:" + userFlag + "断开连接");
		SocketUtil.connectMap.remove(userFlag,client);
	}
}
